﻿using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using AutoLoL.Entities;
using AutoLoL.Logic.Parsers;
using AutoLoL.Shared;
using HelixToolkit;

namespace AutoLoL.Logic.Utils
{
    public class ModelConverter
    {
        public static Model3D GetFromSkin(Skin skin)
        {
            BitmapSource bitmap = ImageParser.DdsToBitmapSource(skin.DdsRafFile.Data);
            Brush brush = new ImageBrush(bitmap);

            string tempFileName = "temp.skn";

            // Save the skin file
            using (FileStream stream = new FileStream(tempFileName, FileMode.Create, FileAccess.ReadWrite))
            {
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write(skin.SknRafFile.Data);
                writer.Close();
            }

            //  Get the obj data
            string objData = SknParser.SknToObj(tempFileName);

            // Try to delete the temp file
            try { File.Delete(tempFileName); }
            catch { if (Debugger.IsAttached) throw; }

            byte[] byteArray = Encoding.ASCII.GetBytes(objData);
            MemoryStream objStream = new MemoryStream(byteArray);

            ObjReader reader = new ObjReader();
            Model3DGroup group = reader.Read(objStream);
            GeometryModel3D model = group.Children[0] as GeometryModel3D;
            MaterialGroup materialGroup = model.Material as MaterialGroup;
            DiffuseMaterial material = materialGroup.Children[0] as DiffuseMaterial;
            material.Brush = brush;
            return group;
        }
    }
}
